package com.swxc.smartorder.ui.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.Gravity
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.FrameLayout
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.model.HttpParams
import com.swxc.smartorder.R
import com.swxc.smartorder.adapter.AdapterWork
import com.swxc.smartorder.app.Config
import com.swxc.smartorder.app.GlobalAPI
import com.swxc.smartorder.entity.CommonData
import com.swxc.smartorder.entity.CommonListData
import com.swxc.smartorder.entity.OrderBean
import com.swxc.smartorder.network.NetworkHelper
import com.swxc.smartorder.ui.base.BaseActivity
import com.swxc.smartorder.utils.DisplayUtil
import com.swxc.smartorder.utils.JsonUtil
import com.swxc.smartorder.widget.CustomLoadMoreView
import kotlinx.android.synthetic.main.activity_order_search.*
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager
import java.util.*

class OrderSearchActivity : BaseActivity() {


    private var tvNumber: TextView? = null
    private var headerView: View? = null
    private var statusLayoutManager: StatusLayoutManager? = null
    private var mHelper: NetworkHelper? = null
    private var mList: MutableList<OrderBean>? = null
    private var mAdapter: AdapterWork? = null
    private var currentPage: Int = Config.PAGE_START
    private var pageSize: Int = Config.PAGE_SIZE
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_order_search)

        initViewAndEvent()
    }


    /**
     * 初始化视图
     */
    @SuppressLint("SetTextI18n")
    private fun initViewAndEvent() {
        val emptyView = layoutInflater.inflate(R.layout.layout_empty, null, false)
        val tvEmpty = emptyView.findViewById<TextView>(R.id.tv_empty)

        headerView = layoutInflater.inflate(R.layout.search_header, null, false)
        tvNumber = headerView?.findViewById(R.id.tv_number)
        val layoutParams = tvEmpty.layoutParams as FrameLayout.LayoutParams
        layoutParams.gravity = Gravity.TOP
        layoutParams.gravity = Gravity.CENTER_HORIZONTAL
        layoutParams.topMargin = DisplayUtil.dip2px(mContext, 40f)

        mHelper = NetworkHelper(mContext, supportFragmentManager)
        tv_cancel.setOnClickListener { finish() }
        edt_search.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val searchContent = edt_search.text.toString()
                currentPage = 1
                search(searchContent, false)
                tvEmpty.text = "哎呀!\n没有找到 $searchContent 相关工单"
                return@OnEditorActionListener true
            }
            false
        })
        statusLayoutManager = StatusLayoutManager.Builder(rv_search)
                .setEmptyLayout(emptyView)
                .setDefaultLayoutsBackgroundColor(Color.WHITE)
                .setOnStatusChildClickListener(object : OnStatusChildClickListener {
                    override fun onErrorChildClick(p0: View?) {
                    }

                    override fun onEmptyChildClick(p0: View?) {
                    }

                    override fun onCustomerChildClick(p0: View?) {
                    }
                })
                .build()
        mList = ArrayList()
        mAdapter = AdapterWork(mList)
        rv_search.layoutManager = LinearLayoutManager(mContext)
        rv_search.adapter = mAdapter
        mAdapter?.setOnItemClickListener { adapter, _, position ->
            val item: OrderBean = adapter.data[position] as OrderBean
            val bundle = Bundle()
            bundle.putLong("orderID", item.id)
            readyGo(OrderDetailActivity::class.java, bundle)
        }

        mAdapter?.setLoadMoreView(CustomLoadMoreView())
        mAdapter?.setOnLoadMoreListener(BaseQuickAdapter.RequestLoadMoreListener {
            if (currentPage == 1) {
                currentPage++
            }
            search(edt_search.text.toString(), true)
        }, rv_search)


    }

    /**
     * 搜索工单
     */

    private fun search(searchContent: String, isLoademore: Boolean) {
        if (searchContent.isEmpty()) {
            showToastCommon("请输入你想要搜索的内容")
        } else {
            val httpParams = HttpParams()
            httpParams.put("chose", "all")
            httpParams.put("fields", "id,status,title,createTime,priorityLevel,timeout")
            httpParams.put("page.pn", currentPage)
            httpParams.put("page.size", pageSize)
            httpParams.put("searchKeyWord", searchContent)
            mHelper?.getRequest(GlobalAPI.orderList, httpParams, object : NetworkHelper.NetWorkHelperBack {
                override fun requestSuccess(json: String) {
                    val type = object : TypeToken<CommonData<CommonListData<OrderBean>>>() {}.type
                    val fromJson = JsonUtil.fromJson<CommonData<CommonListData<OrderBean>>>(json, type)
                            ?: return
                    if (fromJson.success) {

                        val size = fromJson.data.elements.size
                        if (isLoademore) {
                            when {
                                size > 0 -> {
                                    mList?.addAll(fromJson.data.elements)
                                    mAdapter?.notifyDataSetChanged()
                                }
                                size == 0 || size < pageSize -> {
                                    mAdapter?.loadMoreEnd(false)
                                }
                                else -> {
                                    mAdapter?.loadMoreComplete()
                                }
                            }

                        } else {

//                            mAdapter?.setEnableLoadMore(true)
                            when (size) {
                                0 -> {
                                    statusLayoutManager?.showEmptyLayout()
                                }
                                else -> {
                                    tvNumber?.text = "" + fromJson.data.totalAmount
                                    mAdapter?.removeAllHeaderView()
                                    mList?.clear()
                                    mAdapter?.addHeaderView(headerView)
                                    statusLayoutManager?.showSuccessLayout()
                                    mList?.addAll(fromJson.data.elements)
                                    mAdapter?.notifyDataSetChanged()
                                }
                            }
                        }


                    }
                }

                override fun requestFail() {
                    mAdapter?.setEnableLoadMore(true)
                    mAdapter?.loadMoreFail()
                }
            })

        }
    }
}
